var express = require('express');
var router = express.Router();
module.exports = exports = router;
var debug = require('debug')('admin');


router.get('/', function (req, res, next) {
    // if login -> admin main page
    // else -> login
    if (req.session.adminId) {
        debug('has session.adminId =' + req.session.adminId);
        res.redirect('/html/admin/main.html');
    } else {
        debug('no session.adminId');
        res.redirect('/html/admin/login.html');
    }
});

// use res.sendFile, js could not load (relative path)
// var path = require('path');
// var myUtils = require('../../lib/myUtils.js');
// router.get('/', function(req, res, next) {
// 	var staticFolder = myUtils.getStaticFolder();
// 	if (req.session.adminId) {
// 		res.sendFile(path.join(staticFolder, '/html/admin', 'main.html'));
// 	} else {
// 		res.sendFile(path.join(staticFolder, '/html/admin', 'login.html'));
// 	}
// });

var bodyParser = require('body-parser');
router.post('/login', function (req, res, next) {
    bodyParser.json()(req, res, function () {
        next();
    });
});

var AdminDao = require('../../modelDao/adminDao.js');
router.post('/login', function (req, res, next) {
    var loginId = req.body.loginId; // nameOrEmail
    var password = req.body.password;
    debug('login, loginId=' + loginId + ",password=" + password);

    AdminDao.isMatch(loginId, password)
        .then(function resolve(reply) {
            debug('db return succ');
            req.session.adminId = loginId;
            res.status(reply.errcode).send(JSON.stringify(reply.errmsg));
        }, function reject(err) {
            debug('fail');
            res.status(err.errcode).send(JSON.stringify(err.errmsg));
        });
});
